<template>
    <div>
        <div class="order-product-hd">
            <el-row>
                <el-col :span="7"><span class="y-label">{{$t('table.package')}}</span>
                    <el-select v-model="orderData.group_id" class="filter-days" :placeholder="$t('placeholder.select')" style="width: 160px;" size="mini" @change="changePackage($event)">
                        <el-option v-for="(item, index) in groupList" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </el-col>
                <el-col :span="5"><span class="y-label">No. of Days</span>
                    <el-select v-model="orderData.day" class="filter-days" :placeholder="$t('placeholder.select')"  style="width: 60px;" size="mini" @change="changeDay">
                        <el-option v-for="(item, index) in days" :key="index" :label="item" :value="item" />
                    </el-select>
                </el-col>
                <el-col :span="6"><span class="y-label">Date</span>
                    <el-date-picker
                        v-model="orderData.scheduled_at"
                        type="date"
                        :placeholder="$t('placeholder.date')" size="mini" value-format="yyyy-MM-dd" @change="changeScheduled" style=" width: 150px;">
                    </el-date-picker></el-col>
                <el-col :span="6"><span class="y-label">Total</span> <el-input v-model="orderData.total" name="filterTotal"  style="width: 100px;" size="mini" /></el-col>
            </el-row>
        </div>
        <div class="order-product-main" v-if="orderData.group.length > 0" v-for="(group, index) in orderData.group" :key="index">
            <group-product :idx="idx" :key-idx="index" :location-options="locationOptions" :custom-group-id="customGroupId" :product-options="productOptions" :start-date="orderData.scheduled_at" :group-options="groupList" :order-data="group" :home-locations="group.home_locations" :products="productDatas" :home-list="homeList" @change-group="changeGroup" @delivery-change="deliveryChange" @area-change="areaChange" @address-change="addressChange"></group-product>
        </div>
    </div>
</template>

<script>
import i18n from '@/lang/index'
import GroupProduct from '@/components/GroupProduct'
import { groupBy, formatData, urlEncode } from '@/utils'
import { fetchAll } from '@/api/location'
export default {
    name: 'Order-info-list',
    components: {
        GroupProduct
    },
    props: {
        orders: {
            type: Object,
            default () {
                return {}
            }
        },
        products: {
            type: Array,
            default () {
                return []
            }
        },
        productOptions: {
            type: Array,
            default () {
                return []
            }
        },
        orderDatas: {
            type: Object,
            default () {
                return {}
            }
        },
        locationOptions: {
            type: Array,
            default () {
                return []
            }
        },
        groupList: {
            type: Array,
            default () {
                return []
            }
        },
        idx: Number,
        homeList: Array,
        customGroupId: Number
    },
    data () {
        return {
            lang: i18n.locale,                 
            days: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            orderData: JSON.parse(JSON.stringify(this.orderDatas)),
            prices: [],
            productDatas: JSON.parse(JSON.stringify(this.products)),
            ordersObj: JSON.parse(JSON.stringify(this.orders)),
            groups: JSON.parse(JSON.stringify(this.orderDatas.group))
            
        }
    },
    /* computed: {
        retTotal: function() {
            let prices = this.prices, total = 0
            let sorted = groupBy(this.orderData.group, function(item){
                return [item.id];
            })
            for (let j = 0; j < sorted.length; j++) {
                for (let i = 0; i < prices.length; i++) {
                   if (sorted[j][0].id === prices[i].group_id && sorted[j].length === prices[i].qty) {
                        total += prices[i].price
                    } else if (sorted[j][0].id === prices[i].group_id && prices[i].qty === 1) {
                        total += prices[i].price * sorted[j].length
                    }
                }
            }
            this.orderData.total = total
            return total
        }
    }, */
    mounted() {
        this.getPrices(this.orderDatas.group_id)
        this.getTotal()
    },
    watch: {
        orderDatas: function (val) {
            this.orderData = JSON.parse(JSON.stringify(val))
            this.groups = JSON.parse(JSON.stringify(val.group))
            this.getPrices(val.group_id)
            this.getTotal()
        }
    },
    methods: {
        getPrices(el) {
            let data ={}
            for (let i=0; i<this.groupList.length; i++) {
                if(this.groupList[i].id === el) {
                    data = JSON.parse(JSON.stringify(this.groupList[i]))
                    data.group_id = data.id
                    data.area_region_id = ''
                    data.product.forEach(element => {
                        element.qty = element.dqty || element.dqty === 0 ? element.dqty : 1
                        delete element.product_lang
                        return element
                    })
                }
            }
            this.prices = data.price
        },
        changePackage(el) {
            let groupData = {}
            if (this.groupList.length > 0) {
                for (let j = 0; j < this.groupList.length; j++) {
                    if(this.groupList[j].id === el) {
                        groupData = JSON.parse(JSON.stringify(this.groupList[j]))
                    }
                }
            }
            if (this.groups.length > 0) {
                for (let i = 0; i < this.groups.length; i++) {
                    this.groups[i] = JSON.parse(JSON.stringify(groupData))
                    let date = new Date(this.orderData.scheduled_at)
                    date.setTime(date.getTime() + 3600 * 1000 * 24 * (i))
                    this.groups[i].scheduled_at = date
                    this.groups[i].product.forEach(element => {
                        element.qty = element.dqty || element.dqty === 0 ? element.dqty : 1
                        delete element.product_lang
                        return element
                    })
                    this.groups[i].group_id = el
                }
            } else {
                this.groups[0] = JSON.parse(JSON.stringify(groupData))
                let date = new Date(this.orderData.scheduled_at)
                date.setTime(date.getTime() + 3600 * 1000 * 24 * (0))
                this.groups[0].scheduled_at = date
                this.groups[0].product.forEach(element => {
                    element.qty = element.dqty || element.dqty === 0 ? element.dqty : 1
                    delete element.product_lang
                    return element
                })
                this.groups[0].group_id = el
            }
            this.orderData.group = JSON.parse(JSON.stringify(this.groups))
            this.getPrices(el)
            this.getTotal()
            /* this.productDatas = this.orderData.package.product
            this.prices = this.orderData.package.price */
            /* let groupData = data
            groupData.group_id = data.id
            groupData.area_region_id = '' */
        },
        changeDay() { // 修改天数
            let len = this.groups.length, day = this.orderData.day
            if (day < len) {
               this.groups.splice(day, len - day)
            } else {
                for (let i = 0; i < day; i++) {
                    let date = new Date(this.orderData.scheduled_at)
                    date.setTime(date.getTime() + 3600 * 1000 * 24 * (i))
                    if (i >= len) {
                        let groupData = JSON.parse(JSON.stringify(this.groups[0]))
                        groupData.scheduled_at = date
                        this.groups.push(groupData)
                    } else {
                        this.groups[i].scheduled_at = date
                    }
                }
            }
            console.log(this.groups)
            /* this.groups.forEach((ele, i) => {
                let date = new Date(this.orderData.scheduled_at)
                date.setTime(date.getTime() + 3600 * 1000 * 24 * (i))
                ele.scheduled_at = date
                return ele
            }) */
            this.orderData.group = JSON.parse(JSON.stringify(this.groups))
            this.getPrices(this.groups[0].group_id)
            this.getTotal()
        },
        changeScheduled() {
            this.groups.forEach((ele, i) => {
                let date = new Date(this.orderData.scheduled_at)
                date.setTime(date.getTime() + 3600 * 1000 * 24 * (i))
                ele.scheduled_at = date
                return ele
            })
            this.orderData.group = JSON.parse(JSON.stringify(this.groups))
            this.$emit('change-data', this.idx, this.orderData)
        },
        retScheduled(day) {
            let date = new Date(this.orderData.scheduled_at)
            date.setTime(date.getTime() + 3600 * 1000 * 24 * (day))
            return date
        },
        getTotal() {
            // let groups = this.orderData.group
            let prices = this.prices, total = 0, freight = 0
            let sorted = groupBy(this.orderData.group, function(item){
                return [item.group_id]
            })
            for (let j = 0; j < sorted.length; j++) {
                console.log(sorted[j][0].freight)
                if (sorted[j][0].freight) {
                    freight += sorted[j][0].freight
                }
            }
            if (prices && prices.length > 0) {
                for (let i = 0; i < prices.length; i++) {
                    if (this.orderData.group.length === prices[i].qty) {
                        total += prices[i].price
                    }/*  else if (sorted[j].length > prices[i].qty ) {
                        total += prices[i].price * sorted[j].length
                    } */
                }
            }
            this.orderData.total = total
            this.orderData.delivery += parseInt(freight)
            console.log('delivery', this.orderData.delivery)
            this.$emit('change-data', this.idx, this.orderData)
        },
        changeGroup (data, index, isCustom) {
            this.groups[index] = data
            this.orderData.group = JSON.parse(JSON.stringify(this.groups))
            let groupId = this.customGroupId
            if (this.groups.length === 1) {
                this.orderData.group_id = this.orderData.group[0].group_id
                this.productDatas = this.orderData.group[0].product
                groupId = this.orderData.group[0].group_id
            } else if (isCustom) {
                this.orderData.group_id = this.customGroupId
                this.productDatas = this.orderData.group[0].product
            }
            this.getPrices(groupId)
            this.getTotal()
            /* for (let i = 0; i < this.groups.length; i++) {
                this.groups[i] = JSON.parse(JSON.stringify(data))
            } */
            // this.productDatas = JSON.parse(JSON.stringify(data.product))
            // this.ordersObj.assemble[this.idx] = this.orderData
            // this.$emit('change-data', this.idx, this.orderData)
        },
        deliveryChange (index, val, isShow, data) {
            /* let _this = this
            if(this.groups.length > 0 && index === 0){
                this.groups.forEach((element, i) => {
                    // if (i > 0) {
                    element = data
                    element.location_id = val
                    element.area_region_id = ''
                    // }
                    _this.orderData.group[i] = element
                    return element
                })
            } */
            if(index === 0){
                for (var i=0; i < this.groups.length; i++) {
                    this.groups[i].location_id = val
                    this.groups[i].location_name = data.location_name
                    this.groups[i].area_region_id = data.area_region_id
                    this.groups[i].freight = data.freight
                    this.groups[i].delivery = data.delivery
                    this.groups[i].home_locations = data.home_locations
                    this.groups[i].area_region_name = data.area_region_name
                }
                this.orderData.group = JSON.parse(JSON.stringify(this.groups))
            } else {
                this.groups[index].location_id = val
                this.groups[index].location_name = data.location_name
                this.groups[index].area_region_id = ''
                this.groups[index].freight = 0
                this.groups[index].delivery = 0
                this.groups[index].home_locations = data.home_locations
                this.groups[index].area_region_name = ''
                this.orderData.group[index] = JSON.parse(JSON.stringify(this.groups[index]))
            }
            this.$emit('change-data', this.idx, this.orderData)
        },
        areaChange (index, val, freight, isFirst, data) {
            var fri = 0
            this.groups[index].area_region_id = val
            this.groups[index].freight = freight
            this.groups[index].delivery = freight
            this.groups[index].area_region_name = data.area_region_name
            for (var i=0; i < this.groups.length; i++) {
                //if (i > 0 && index === 0 && !isFirst ) {
                if (index === 0 && !isFirst) {
                    this.groups[i].area_region_id = val
                    this.groups[i].area_region_name = data.area_region_name
                    this.groups[i].freight = freight
                    this.groups[i].delivery = freight
                }
                //}
                if (this.groups[i].freight) {
                    fri = fri + parseFloat(this.groups[i].freight)
                }
            }
            this.orderData.freight = fri
            this.orderData.group = JSON.parse(JSON.stringify(this.groups))
            this.$emit('change-data', this.idx, this.orderData)
        },
        addressChange(index, val){
            if (index === 0) {
                for (var i=0; i < this.groups.length; i++) {
                    this.groups[i].address = val
                }
            }
            this.orderData.group = JSON.parse(JSON.stringify(this.groups))
            this.$emit('change-data', this.idx, this.orderData)
        }
        /* addressChange (index, val, freight, groupData) {
            var fri = 0
            this.groups[index] = groupData
            for (var i=0; i < this.groups.length; i++) {
                if (i > 0 && index === 0) {
                    this.groups[i].area_region_id = val
                    this.groups[i].delivery = groupData.delivery
                }
                if (this.groups[i].delivery) {
                    fri = fri + parseFloat(this.groups[i].delivery)
                }
            }
            this.orderData.delivery = fri
            this.orderData.group = this.groups
            this.$emit('change-data', this.idx, this.orderData)
        }
        changeAll (data, index) {
            let len = this.orderData.day
            for (let i = 0; i < len; i++) {
                if (i !== index) {
                    this.orderData.group[i].group_id = data.id
                    this.orderData.group[i].product = data.product
                } else {
                    this.orderData.group[i] = data
                }
            }
            console.log(this.orderData.group)
        } */
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .order-product-hd{
        height: 40px;
        padding: 5px;
        background: #409eff;
        .y-label{
            color: #fff;
        }
    }
    .order-product-main{
        margin-top:10px;
        line-height: 20px;
        font-size: 12px;
    }
</style>
